<?php

namespace app\admin\controller;

use app\admin\validate\CoinAddressValidate;
use app\service\CoinAddressService;
use app\service\MemberService;
use think\exception\ValidateException;

class CoinAddress extends Admin
{
    public function __construct(CoinAddressService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "提现地址列表");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $email = $params['email'];
        $memberId = $params['member_id'];
        $memberIds = [];
        $status = $params['status'];
        $where = [];
        if (!empty($params["create_at"])) {
            $between = explode(" - ", $params["create_at"]);
            if (count($between) == 2) {
                $where[] = ['create_at', 'between', [$between[0], $between[1]]];
            }
        }
        if (!empty($email)) {
            $memberService = $this->app->make(MemberService::class);
            $memberIds = $memberService->Column([["email", "like", "%$email%"]], "id");
            if (empty($memberIds)) {
                $ret = ["rows" => [
                    "total" => 0,
                    "list" => [],
                ]];
                $this->result($ret);
            }
        }
        if (!empty($memberId)) {
            array_push($memberIds, $memberId);
        }
        if (!empty($memberIds)) {
            $where[] = ['member_id', 'in', $memberIds];
        }
        if (!empty($status)) {
            $where[] = ['status', '=', $status];
        }
        $ret = $this->service->getList($where, "*", ["member"]);
        int_to_string($ret["rows"]["list"], ["status" => ["-1" => "驳回", "1" => "审核中", "2" => "通过"]]);
        $this->result($ret);
    }

    public function audit()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "审核");
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id, ["*"]);
            $this->assign("vo", $vo);
            return $this->fetch("audit");
        }
        $params = $this->request->Post();
        $data["status"] = $params["status"];
        $data["id"] = $params["id"];
        try {
            validate(CoinAddressValidate::class)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->save($data);
        if ($ret) {
            $this->success("操作成功");
        } else {
            $this->error("保存失败");
        }
    }
}